package com.huaxin.hxrabbitmq.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class MessageSender {

    private final RabbitTemplate rabbitTemplate;

    // 可以从配置文件读取默认值
    @Value("${app.rabbitmq.default.exchange:app.message.exchange}")
    private String defaultExchange;

    @Value("${app.rabbitmq.default.routing-key:notification.send}")
    private String defaultRoutingKey;

    public MessageSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 发送消息到指定 exchange + routingKey
     */
    public void send(String exchange, String routingKey, Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 使用默认 exchange 和 routingKey 发送
     */
    public void send(Object message) {
        send(defaultExchange, defaultRoutingKey, message);
    }

    /**
     * 发送带消息ID的消息（可用于幂等控制）
     */
    public void sendWithId(String exchange, String routingKey, Object message) {
        var messagePostProcessor = (org.springframework.amqp.core.MessagePostProcessor) mp -> {
            mp.getMessageProperties().setMessageId(UUID.randomUUID().toString());
            return mp;
        };
        rabbitTemplate.convertAndSend(exchange, routingKey, message, messagePostProcessor);
    }
}